package com.yu.crm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.domain.dto.WxCpUserReq;
import com.yu.crm.domain.pojo.CrmDepartment;
import com.yu.crm.domain.pojo.CrmDepartmentMember;
import com.yu.crm.domain.pojo.CrmUser;
import com.yu.crm.domain.pojo.CrmUserRole;
import com.yu.crm.feign.remote.CrmUserFeignRemote;
import com.yu.crm.mapper.CrmDepartmentMemberMapper;
import com.yu.crm.service.CrmDepartmentMemberService;
import com.yu.crm.service.CrmDepartmentService;
import com.yu.crm.service.CrmUserRoleService;
import com.yu.crm.service.CrmUserService;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ExceptionHelpers;
import com.yxzz.common.helper.IDHelper;
import me.chanjar.weixin.cp.bean.Gender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 部门成员表 服务实现类
 * </p>
 *
 * @author donnie-bin
 * @since 2019-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmDepartmentMemberServiceImpl extends ServiceImpl<CrmDepartmentMemberMapper, CrmDepartmentMember> implements CrmDepartmentMemberService{

    @Autowired
    CrmUserService userService;

    @Autowired
    CrmUserRoleService userRoleService;

    @Autowired
    CrmDepartmentService departmentService;

    @Autowired
    private CrmUserFeignRemote crmUserFeignRemote;

    @Override
    public boolean saveOrUpdate(CrmDepartmentMember entity) {
        //获取最大的工号(数字部分)
        Integer s = baseMapper.maxMemberNo();
        if (DataHelpers.isEmpty(entity.getId())) {
            CrmUser user = new CrmUser();
            user.setUserId(IDHelper.getRandomIdByUUID());
            user.setUserName(entity.getMemberName());
            user.setUserAvatarUrl(entity.getUserAvatarUrl());
            user.setUserSex(entity.getUserSex());
            user.setUserBirthday(entity.getUserBirthday());
            user.setUserPhone(entity.getUserPhone());
            ExceptionHelpers.checkData(userService.save(user), "新增失败");

            List<CrmUserRole> userRoles = new ArrayList<>();
            if (DataHelpers.isNotEmpty(entity.getRoleList())) {
                entity.getRoleList().forEach(role -> {
                    CrmUserRole userRole = new CrmUserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(role.getId());
                    userRoles.add(userRole);
                });
            }
            ExceptionHelpers.checkData(userRoleService.saveBatch(userRoles), "新增失败");

            entity.setUserId(user.getUserId());
            entity.setGmtCreate(DateHelpers.now());
            entity.setGmtModified(DateHelpers.now());
            entity.setMemberNo(maxMemberNo(s));
            ExceptionHelpers.checkData(super.save(entity), "新增失败");
            //调用企业微信接口
            WxCpUserReq req=new WxCpUserReq();
            if(DataHelpers.isNotEmpty(entity.getUserId())){
                req.setUserId(entity.getUserId());
            }
            if(DataHelpers.isNotEmpty(entity.getMemberName())){
                req.setName(entity.getMemberName());
            }else{
                throw new GeneralException("姓名不能为空");
            }
            if(DataHelpers.isNotEmpty(entity.getUserPhone())){
                req.setMobile(entity.getUserPhone());
            }else{
                throw new GeneralException("手机号码不能为空");
            }
            if(DataHelpers.isNotEmpty(entity.getDepartmentId())){
                Long[] ids={entity.getDepartmentId()};
                req.setDepartIds(ids);
            }else{
                throw new GeneralException("所属部门不能为空");
            }
            //设置性别
            if(DataHelpers.isNotEmpty(entity.getUserSex())){
                req.setGender(Gender.fromCode(entity.getUserSex().toString()));
            }
            if(DataHelpers.isNotEmpty(entity.getUserAvatarUrl())){
                req.setAvatar(entity.getUserAvatarUrl());
            }
            req.setAgentId(1000012);
            System.out.println("========test"+req);
//            crmUserFeignRemote.createUser(req);
            System.out.println("========"+req);
            return true;
        } else if (DataHelpers.isNotEmpty(entity.getUserId())) {

            CrmUser user = new CrmUser();
            user.setUserId(entity.getUserId());
            user.setUserName(entity.getMemberName());
            user.setUserAvatarUrl(entity.getUserAvatarUrl());
            user.setUserSex(entity.getUserSex());
            user.setUserBirthday(entity.getUserBirthday());
            user.setUserPhone(entity.getUserPhone());
            QueryWrapper<CrmUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id", entity.getUserId());
            CrmUser oldUser = userService.getOne(userQueryWrapper);
            if (DataHelpers.isNotEmpty(oldUser)) {
                user.setId(oldUser.getId());
                ExceptionHelpers.checkData(userService.updateById(user), "更新失败");
            } else {
                ExceptionHelpers.checkData(userService.save(user), "更新失败");
            }

            List<CrmUserRole> userRoles = new ArrayList<>();
            if (DataHelpers.isNotEmpty(entity.getRoleList())) {
                entity.getRoleList().forEach(role -> {
                    CrmUserRole userRole = new CrmUserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(role.getId());
                    userRoles.add(userRole);
                });
            }
            QueryWrapper<CrmUserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", entity.getUserId());
            if (userRoleService.remove(userRoleQueryWrapper)) {
                ExceptionHelpers.checkData(userRoleService.saveBatch(userRoles), "更新失败");
            } else {
                ExceptionHelpers.throwGeneralException("更新失败");
            }
            //更新工号
            if(!DataHelpers.isNotEmpty(entity.getMemberNo())){
                entity.setMemberNo(maxMemberNo(s));
            }

            entity.setGmtCreate(DateHelpers.now());
            entity.setGmtModified(DateHelpers.now());
            ExceptionHelpers.checkData(super.updateById(entity), "更新失败");

            //调用企业微信接口
            WxCpUserReq req=new WxCpUserReq();
            if(DataHelpers.isNotEmpty(entity.getUserId())){
                req.setUserId(entity.getUserId());
            }else{
                throw new GeneralException("用户编号不能为空");
            }
            if(DataHelpers.isNotEmpty(entity.getMemberName())){
                req.setName(entity.getMemberName());
            }
            if(DataHelpers.isNotEmpty(entity.getUserPhone())){
                req.setMobile(entity.getUserPhone());
            }
            if(DataHelpers.isNotEmpty(entity.getDepartmentId())){
                Long[] ids={entity.getDepartmentId()};
                req.setDepartIds(ids);
            }
            req.setAgentId(1000012);
            crmUserFeignRemote.updateUser(req);
            return true;
        } else {
            ExceptionHelpers.throwGeneralException("更新时用户ID不能为空");
            return false;
        }
    }

    @Override
    public CrmDepartmentMember getById(Serializable id) {
        return baseMapper.getById(id);
    }

    @Override
    public boolean removeById(Serializable id) {
        //QueryWrapper<CrmUserRole> userRoleQueryWrapper = new QueryWrapper<>();
        //userRoleQueryWrapper.eq("user_id", entity.getUserId());
        CrmDepartmentMember member = baseMapper.selectById(id);
        if(DataHelpers.isNotEmpty(member)){
            HashMap<String,Object> map=new HashMap<>();
            map.put("agentId",1000012);
            map.put("userIds",member.getUserId());
            //删除用户
            crmUserFeignRemote.deleteUser(map);

            QueryWrapper<CrmUser> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("user_id",member);
            queryWrapper.eq("is_deleted",0);
            userService.remove(queryWrapper);

            return super.removeById(id);
        }
        return false;
    }

    @Override
    public IPage<CrmDepartmentMember> list(IPage<CrmDepartmentMember> page, CrmDepartmentMember queryInfo) {
        if(queryInfo.getDepartmentId() != null){
            List<CrmDepartment> crmDepartmentTree = departmentService.treeList(queryInfo.getDepartmentId());
            List<Long> crmDepartmentIds = new ArrayList<>();
            crmDepartmentIds.add(queryInfo.getDepartmentId());
            this.tree2List(crmDepartmentTree, crmDepartmentIds);
            return baseMapper.list(page, queryInfo, crmDepartmentIds);
        }else{
            return baseMapper.list(page, queryInfo, null);
        }
    }

    @Override
    /**
     * 通过用户id查询用户所在部门
     * @param userId
     * @return
     */
    public CrmDepartmentMember infoByUserId(String userId){
        try {
            QueryWrapper<CrmDepartmentMember> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("is_deleted",0);
            return baseMapper.selectOne(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 树形结构转集合
     * @param tree
     * @param list
     */
    private void tree2List(List<CrmDepartment> tree, List<Long> list){
        tree.stream().forEach(node -> {
            list.add(node.getId());
            if(CollUtil.isNotEmpty(node.getChildren())){
                tree2List(node.getChildren(), list);
            }
        });
    }

    /**
     * 拼接工号
     * @param s
     * @return
     */
    public String maxMemberNo(Integer s){
        //前缀
        String start="whyxci_";
        Integer end=1;
        if(DataHelpers.isNotEmpty(s)){
            //String start = s.substring(0,7);
            //end = Integer.parseInt(s.substring(7));
            end=s+1;
        }
        start=start+end;
        return start;
    }
}
